package hut.lgl.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class JdbcUtil<T> {
    private static QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
    //增删改操作
    public int update(String sql,Object...params){
        int row = 0;
        try {
            row = qr.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    //查询所有信息
    public List<T> getAll(String sql,Class<? extends T> clazz,Object...params){
        List<T> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<>(clazz), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //查询一条记录
    public T getOne(String sql,Class<? extends T> clazz,Object...params){
        T t = null;
        try {
            t = qr.query(sql,new BeanHandler<>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return t;
    }

    //查询某一列
    public int getColumn(String sql,Object...params){
        Object obj = null;
        try {
            obj = qr.query(sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(obj.toString());
    }
}
